import { OPT_MAP_ENUM } from 'constants/index';
import { useState } from 'react';
import { MessagePlugin as Message } from 'tdesign-react';

export function useSingleMessage() {
  const [currentMessageId, setCurrentMessageId] = useState<string | null>(null);

  const showMessage = (type?: any, content?: string, duration = 3000) => {
    // 如果已经有消息正在显示，则先关闭它
    if (currentMessageId) {
      Message.close(currentMessageId);
    }

    // 显示新的消息并获取其ID
    // @ts-ignore
    const newMessageId = Message[['error', 'success'].includes(type) ? type : 'success']({
      content: content || OPT_MAP_ENUM[type],
      duration,
      onClose: () => setCurrentMessageId(null),
    });

    // 更新当前消息ID
    setCurrentMessageId(newMessageId);
  };

  return { showMessage };
}
